package router

import (
	"crypto/hmac"
	"crypto/sha256"
	"dhuviewer/jwt"
	services "dhuviewer/services"
	"encoding/hex"
	"fmt"

	"github.com/gin-gonic/gin"
)

func hmacSha256(data string, secret string) string {
	h := hmac.New(sha256.New, []byte(secret))
	h.Write([]byte(data))
	return hex.EncodeToString(h.Sum(nil))
}

func Login(rg *gin.RouterGroup) {
	LoginRouter := rg.Group("/")

	LoginRouter.GET("/", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"ok": 1,
		})
	})
	LoginRouter.POST("/reg", func(c *gin.Context) {
		regJSON := make(map[string]interface{}) //注意该结构接受的内容
		c.ShouldBind(&regJSON)
		fmt.Println(regJSON)
		hashed := hmacSha256(regJSON["password"].(string)+"0x0", "just4fun")
		uid, err := services.CreateLogin(regJSON["email"].(string), hashed)
		if err != nil {
			c.JSON(200, gin.H{
				"status": 40000,
			})
			return
		}
		err = services.CreateSocail(uid, regJSON["username"].(string))
		if err != nil {
			c.JSON(200, gin.H{
				"status": 40000,
			})
			return
		}
		services.CreateUser(uid)
		err = services.CreateSub(uid)
		if err != nil {
			c.JSON(200, gin.H{
				"status": 40000,
			})
		} else {
			c.JSON(200, gin.H{
				"status": 20000,
				"uid":    uid,
			})
		}
	})

	LoginRouter.POST("/auth", func(c *gin.Context) {
		json := make(map[string]interface{}) //注意该结构接受的内容
		c.BindJSON(&json)
		fmt.Println(json)
		//fmt.Println(strings.Contains("seafood", "foo"))
		// services.TestCreate()
		err, Res := services.LoginByEmail(json["email"].(string))
		if err != nil {
			fmt.Println(err)
		} else {
			fmt.Println(Res)

		}
		hashed := hmacSha256(json["password"].(string)+"0x0", "just4fun")
		if hashed == Res.Password {
			err, socailRes := services.GetSocail(Res.Uid)
			if err != nil {
				c.JSON(200, gin.H{
					"status": 40000,
				})
			}
			accessToken, _ := jwt.SignJwt(socailRes.Username.String, socailRes.Level.String, Res.Uid.String())

			c.JSON(200, gin.H{
				"access_token": accessToken,
				"level":        socailRes.Level.String,
				"uid":          socailRes.Uid.String(),
				"status":       20000,
			})
		} else {
			c.JSON(200, gin.H{
				"status": 40000,
			})
		}

	})
}
